package spms.front.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import spms.front.config.Invoker;

@Controller
public class MenuController {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	String serverName = "SPMS-DATA";

	/**AJAX 加载左侧菜单
	**/
	@PostMapping("getMenuList")
	@ResponseBody
	public Object getMenuList() {

		JSONArray ja = Invoker.INSTANCE.invoke(serverName,"/menu/findAll",null, JSONArray.class);

		//sortMenu(ja);


		return Invoker.INSTANCE.invoke(serverName,"/menu/findAll",null, JSONArray.class);
	}
	
	/**跳转菜单列表页面
	 * */
	@GetMapping("/menuList")
	public Object menuList(@RequestParam(defaultValue = "0") Integer pageNum,@RequestParam(defaultValue = "10") Integer pageSize,Model model) {
		getMenuList(pageNum,pageSize,model);
		return "menuList";
	}
	
	/**通过父菜单获取子菜单列表
	 * @param pageNum 页码
	 * @param pageSize 页面大小
	 * */
	@PostMapping("/menuList")
	public Object getMenuList(@RequestParam(defaultValue = "0") Integer pageNum,@RequestParam(defaultValue = "10") Integer pageSize,Model model) {

		MultiValueMap mapParam = new LinkedMultiValueMap();
		mapParam.add("pageNum",pageNum);
		mapParam.add("pageSize",pageSize);
		JSONObject page = (JSONObject) Invoker.INSTANCE.invoke(serverName,"/menu/findPage",mapParam, JSONObject.class);
		model.addAttribute("page", page);
		return "menuList::menuList";
	}

	public void sortMenu(JSONArray jsonArray){
			jsonArray.sort((v1,v2)->{
				JSONObject job1 = (JSONObject)v1;
				JSONObject job2 = (JSONObject)v2;
				if(job1.containsKey("submenu") && !job1.getJSONArray("submenu").isEmpty()){
					JSONArray ja = job1.getJSONArray("submenu");
					sortMenu(ja);
				}
				return job1.getInteger("order").compareTo(job2.getInteger("order"));
			});

	}
}
